#!/bin/bash
# 树莓派 systemd 用户问题诊断脚本

echo "========================================="
echo "  EMS systemd 用户问题诊断"
echo "========================================="
echo

# 1. 检查当前用户
echo "1. 当前登录用户:"
whoami
echo

# 2. 检查 pi 用户是否存在
echo "2. 检查 pi 用户:"
if id pi &>/dev/null; then
    echo "   ✓ pi 用户存在"
    id pi
else
    echo "   ✗ pi 用户不存在"
fi
echo

# 3. 检查 sunfly 用户
echo "3. 检查 sunfly 用户:"
if id sunfly &>/dev/null; then
    echo "   ✓ sunfly 用户存在"
    id sunfly
else
    echo "   ✗ sunfly 用户不存在"
fi
echo

# 4. 检查项目目录权限
echo "4. 项目目录权限:"
ls -ld /home/sunfly/ems-cpp-v1
echo

# 5. 检查可执行文件权限
echo "5. 可执行文件权限:"
if [ -f /home/sunfly/ems-cpp-v1/build/bin/ems-cpp-v1 ]; then
    ls -l /home/sunfly/ems-cpp-v1/build/bin/ems-cpp-v1
else
    echo "   ✗ 可执行文件不存在"
fi
echo

# 6. 查看当前 systemd 配置
echo "6. 当前 systemd 单元配置:"
if [ -f /etc/systemd/system/ems-dispatch.service ]; then
    grep -E "^User=|^Group=|^WorkingDirectory=|^ExecStart=" /etc/systemd/system/ems-dispatch.service
else
    echo "   ✗ systemd 单元文件不存在"
fi
echo

# 7. 测试手动运行
echo "7. 建议测试命令:"
echo "   以当前用户运行:"
echo "   cd /home/sunfly/ems-cpp-v1 && ./build/bin/ems-cpp-v1 --config ./config"
echo
echo "   以 sunfly 用户运行:"
echo "   sudo -u sunfly /home/sunfly/ems-cpp-v1/build/bin/ems-cpp-v1 --config /home/sunfly/ems-cpp-v1/config"
echo

echo "========================================="
echo "诊断完成"
echo "========================================="
